package DAO;

import BUS.AccountMailBUS;
import DTO.MailStructureDTO;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.PasswordAuthentication;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MailDateFormat;
import javax.swing.JOptionPane;
import DTO.*;
import UTIL.ConvertString;
import UTIL.ReadXML;
import UTIL.SqlDataAccessHelper;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.mail.Flags;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.AndTerm;
import javax.mail.search.BodyTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author NxSiHMr0D
 */
public class ExcuteMailDAO {

    private AccountMailDTO _accountMail;
    Store _store;
    Folder _folder;
    //SqlDataAccessHelper _mySQLAccess = new SqlDataAccessHelper();
    Connection _newConnect;
    public void deleteMail(MailStructureDTO mailDelete) throws SQLException, Exception{
          if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
          int IDMail = mailDelete.getIdMail();
          deleteAttachFile(IDMail);
           PreparedStatement uprs =
                _newConnect.prepareStatement("DELETE FROM Mail WHERE IDMail = ?");
            uprs.setInt(1, mailDelete.getIdMail());
        uprs.executeUpdate();
        Message sr[]= searchMailInServer(mailDelete);
        deleteMailOnServer(sr[0]);
          
    }
    private void  deleteAttachFile(int IdMail) throws SQLException{

        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
         PreparedStatement uprs =
                _newConnect.prepareStatement("DELETE FROM FileAttached WHERE IDMail = ?");
        uprs.setInt(1, IdMail);
        uprs.executeUpdate();


    }
    public void diconnectServer() throws SQLException, MessagingException {
        //throw new UnsupportedOperationException("Not yet implemented");
        if( _newConnect != null && !_newConnect.isClosed()){
             _newConnect.close();
//              _folder.close(false);
//            _store.close();
//
           
        }

    }
    public void setMaskMail(int IDMail,int typeMail) throws SQLException{
        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }

        PreparedStatement uprs =
                _newConnect.prepareStatement("UPDATE Mail SET TypeMail = ?" +
                " WHERE IDMail = ?");
        uprs.setInt(1, typeMail);
        uprs.setInt(2, IDMail);
        int st = uprs.executeUpdate();


    }
    public int saveAccount(AccountMailDTO account) throws SQLException {
        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
        int IDSender = 1;
        // String sqlQuerry = "INSERT INTO Accounts(AccountName,MailAddress,IncomingUserName,IncomingServerName,IncomingServerType,OutGoingUserName,OutGoingServerName,Password) VALUES(?,?,?,?,?,?,?,?)";
        //PreparedStatement st = _newConnect.prepareStatement(sqlQuerry);
        account.setIncomingUserName(account.getAccountName());
        Statement uprs = _newConnect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet st = uprs.executeQuery("SELECT * FROM Accounts");
        st.moveToInsertRow();
        st.updateString("AccountName", account.getAccountName());
        st.updateString("MailAddress", account.getMailAddress());
        st.updateString("IncomingUserName", account.getIncomingUserName());
        st.updateString("IncomingServerName", account.getIncommingServerName());
        st.updateString("IncomingServerType", account.getIncomingServerType());
        st.updateString("OutGoingUserName", account.getOutgoingUserName());
        st.updateString("OutGoingServerName", account.getOutgoingServerName());
        st.updateString("Password", account.getPassword());
        //ResultSet res = st.executeQuery();
        st.insertRow();
        st.beforeFirst();
        if (st.next()) {
            //_newConnect.close();
            return st.getInt("ID");
        }
        //return -1;
        return IDSender;
    }

    public int getIDAccount(AccountMailDTO account) throws SQLException {
        //int IDSender = 1;
        String sqlQuerry = "SELECT * FROM Accounts WHERE AccountName = ? and MailAddress=?";
        PreparedStatement st = _newConnect.prepareStatement(sqlQuerry);
        st.setString(1, account.getAccountName());
        st.setString(2, account.getMailAddress());

        ResultSet res = st.executeQuery();
        if (res.next()) {
            // _newConnect.close();
            return res.getInt("ID");
        }
        return -1;
    }

    public void saveAttachFile(int IDMail, ArrayList<File> lstAttachFile) throws SQLException {

        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }

        for (File file : lstAttachFile) {
            Statement uprs = _newConnect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet st = uprs.executeQuery("SELECT * FROM FileAttached");
            st.moveToInsertRow();
            st.updateInt("IDMail", IDMail);
            st.updateString("PathFileAttached", file.getName());
            st.insertRow();
        //st.beforeFirst();
        }
    //ResultSet res = st.executeQuery();


    // return ID;
    }
    public void saveReceiver(int IDMail,String sender) throws SQLException{
        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }


        Statement uprs = _newConnect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet st = uprs.executeQuery("SELECT * FROM Receiver");
        st.moveToInsertRow();
        st.updateInt("IDMail", IDMail);
        st.updateString("EmailAddress",sender);
        st.insertRow();
    //st.beforeFirst();

    }
    public String getReceiver(int IDMail) throws SQLException{
         if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
        String sender = "";
        String sqlQuerry = "SELECT * FROM Receiver WHERE IDMail = ?";
        PreparedStatement st = _newConnect.prepareStatement(sqlQuerry);
        st.setInt(1, IDMail);
        ResultSet res = st.executeQuery();
        while (res.next()) {
            sender = res.getString("EmailAddress");
        }
        return sender;
    }
    public ArrayList<File> getAttachFile(int IDMail) throws SQLException {
        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
        ArrayList<File> lstAttachFile = new ArrayList<File>();
        String sqlQuerry = "SELECT * FROM FileAttached WHERE IDMail = ?";
        PreparedStatement st = _newConnect.prepareStatement(sqlQuerry);
        st.setInt(1, IDMail);
        ResultSet res = st.executeQuery();
        while (res.next()) {
            File file = new File(res.getString("PathFileAttached"));
            lstAttachFile.add(file);

        }
        return lstAttachFile;
    }

    public void saveMail2DataBase(ArrayList<MailStructureDTO> mailList) throws SQLException, UnsupportedEncodingException {
        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
        //Insert Accout mail get Mail List to get ID mail
        //

        int IDSender = 1;
        IDSender = getIDAccount(_accountMail);
        if (IDSender == -1) {
            IDSender = saveAccount(_accountMail);
        }
        for (MailStructureDTO mail : mailList) {
            String sqlQuerry = "INSERT INTO Mail(IDSender,Subject,Content,DateTimeSent,MailIn,TypeMail,ContentHTML,IsAttachFile) VALUES(?,?,?,?,?,?,?,?)";
            PreparedStatement st = _newConnect.prepareStatement(sqlQuerry);
            st.setInt(1, IDSender);
            String convert = ConvertString.ConvertString2UTF8(mail.getTitle());

            //convert = mail.getTitle();

            st.setString(2, convert);
            convert = ConvertString.ConvertString2UTF8(mail.getContent());
            //convert = mail.getContent();
            st.setString(3, convert);
            //java.util.Date utilDate = new java.util.Date();
            java.sql.Date sqlDate = new java.sql.Date(mail.getDateSend().getTime());
            st.setDate(4, sqlDate);
            st.setInt(5, 1);
            st.setInt(6, 1);
            convert = ConvertString.ConvertString2UTF8(mail.getContentHTML());
            st.setString(7, convert);
            st.setBoolean(8, mail.getIsAttachment());
            st.execute();

            int IDMail = MailDAO.getIDMail()+1;
            //Insert AttachFile
            saveAttachFile(IDMail, mail.getAttachFiles());
            convert = mail.getSender();
            saveReceiver(IDMail, convert);
        }
        _newConnect.close();
    }

    public ArrayList<MailStructureDTO> getMailFromDatabase(AccountMailDTO account) throws SQLException, UnsupportedEncodingException, SAXException, ParserConfigurationException, IOException {
        ArrayList<MailStructureDTO> mailList = new ArrayList<MailStructureDTO>();
        if (_newConnect == null || _newConnect.isClosed()) {
            _newConnect = SqlDataAccessHelper.getConnection();
        }
        //AccountMailDAO mailDAO = new AccountMailDAO();

        String sqlQuerry = "SELECT * FROM Mail WHERE IDSender = ?";
        PreparedStatement st = _newConnect.prepareStatement(sqlQuerry);
        //select tu bang Account de lay ra ID
        int IDSender = 1;
        IDSender = getIDAccount(_accountMail);
//        IDSender = ReadXML.getIDDefaultUser();
//        _accountMail = mailDAO.getAccountMail(IDSender);
        if (IDSender == -1) {
            return mailList;
        }
        st.setInt(1, IDSender);
        ResultSet res = st.executeQuery();

        while (res.next()) {
            MailStructureDTO mail = new MailStructureDTO();
            int i = res.getInt("IDMail");
            ArrayList<File> attachFile = getAttachFile(i);
            mail.setAttachFiles(attachFile);
            mail.setIdMail(i);

            String s = res.getString("Subject");
            s = ConvertString.ConvertUTF82String(s);
            mail.setTitle(s);
            s = getReceiver(i);
            mail.setSender(s);
            s = res.getString("Content");
            s = ConvertString.ConvertUTF82String(s);
            mail.setContent(s);

            s = res.getString("ContentHTML");
            s = ConvertString.ConvertUTF82String(s);
            mail.setContentHTML(s);

            Date date = res.getDate("DateTimeSent");
            mail.setDateSend(date);


            i = res.getInt("TypeMail");
            mail.setTypeMail(i);
            i = res.getInt("MailIn");
            mail.setMailIn(i);
            Boolean bol = res.getBoolean("IsAttachFile");
            mail.setIsAttachment(bol);
            //mail.setSender(_accountMail.get)
            mailList.add(mail);

        // System.out.println(i + "\t\t" + s);
        }
        _newConnect.close();
        return mailList;


    }

    private static void saveFile(BodyPart part, String filenameAttach, String dectination) throws MessagingException, IOException {
        //throw new UnsupportedOperationException("Not yet implemented");
        String disposition = part.getDisposition();
        // String contentType = part.getContentType();
        if (disposition == null) { // When just body

            return;
        } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            String attach = part.getFileName();
            if (attach != null && attach.equals(filenameAttach)) {

                saveFile(part.getFileName(), part.getInputStream(), dectination);
            }
        } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
            String attach = part.getFileName();

            if (attach != null && attach.equals(filenameAttach)) {

                saveFile(part.getFileName(), part.getInputStream(), dectination);
            }
        } else {  // Should never happen
            System.out.println("Other: " + disposition);
        }

    }

    public ExcuteMailDAO() throws ParserConfigurationException, SAXException, IOException, Exception {
       
        _accountMail = new AccountMailDTO();
        int idAcc = ReadXML.getIDDefaultUser();
        if ( idAcc == -1)
            throw new Exception("The Default Account do not set !!!");
        AccountMailDAO accountMail = new AccountMailDAO();
        _accountMail = accountMail.getAccountMail(idAcc);
//        _accountMail.setIncomingUserName("nghia.hoctap");
//        _accountMail.setIncomingServerType("pop3s");
//        _accountMail.setIncommingServerName("pop.gmail.com");
//        _accountMail.setPassword("nhannghia");
//        _accountMail.setMailAddress("nghia.hoctap@gmail.com");
//        _accountMail.setAccountName("nghia.hoctap");
//        _accountMail.setIncomingUserName("0612285@student.hcmus.edu.vn");
//          _accountMail.setIncomingServerType("pop3s");
//           _accountMail.setIncommingServerName("pop3.live.com");
//           _accountMail.setPassword("mikyms0s");
    }
    public Message[] searchMailInServer(MailStructureDTO mail) throws Exception {
        connectServer();
        if (_store.isConnected() == false) {
            connectServer();
        }
        if (_folder == null || !_folder.isOpen()) {
            _folder = _store.getFolder("INBOX");
            _folder.open(Folder.READ_WRITE);
        }
        SearchTerm st = new AndTerm(new SubjectTerm(mail.getTitle()), new BodyTerm(mail.getContent()));
        Message[] sr = _folder.search(st);
        return sr;
    }
    private void deleteMailOnServer(Message mailMess) throws MessagingException{
        mailMess.setFlag(Flags.Flag.DELETED, true);
        _folder.close(true);
        _store.close();


    }
    public void saveAttachFile(MailStructureDTO mailAttach, String filenameAttach, String dectination) throws Exception {
        //throw new UnsupportedOperationException("Not yet implemented");
         if (_newConnect == null || _newConnect.isClosed()) {
             connectServer();
            _newConnect = SqlDataAccessHelper.getConnection();
        }
        if (_store.isConnected() == false) {
            connectServer();
        }
        if (_folder == null) {
            _folder = _store.getFolder("INBOX");
            _folder.open(Folder.READ_ONLY);
        }
        SearchTerm st = new AndTerm(new SubjectTerm(mailAttach.getTitle()), new BodyTerm(mailAttach.getContent()));
        // SearchTerm st = new AndTerm
        // _folder.open(Folder.READ_ONLY);

        //Message[] message = _folder.getMessages();
        Message[] sr = _folder.search(st);
        int n = sr.length;
        for (int index = 0; index < n; index++) {
            //if ( message[index].getSubject() == mailAttach.getTitle() )
            //{
            Object content = sr[index].getContent();
            String title = sr[index].getSubject();
            JOptionPane.showMessageDialog(null, title);
            saveFile((Multipart) content, filenameAttach, dectination);
        //}

        }
//    folder.close(false);
    // _store.close();


    }

    private static void saveFile(Multipart multipart, String filenameAttach, String dectination)
            throws MessagingException, IOException {
        for (int i = 0, n = multipart.getCount(); i < n; i++) {
            //handlePart(multipart.getBodyPart(i),mail);
            saveFile(multipart.getBodyPart(i), filenameAttach, dectination);

        }
    }

    private Session getMailSession() throws Exception {
        //Tạo properties rỗng
        Properties props = new Properties();
        props.put("mail.smtp.host", "pop.gmail.com");
//        props.put("mail.smtp.host", "smtp.live.com");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true");
        javax.mail.Authenticator pa = null; //default: no authentication
        if (getAccountMail().getIncomingUserName() != null && getAccountMail().getPassword() != null) {
            props.put("mail.smtp.auth", "true");
            pa = new Authenticator() {

                @Override
                protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                    return super.getPasswordAuthentication();
                }
            };
        }
        return Session.getInstance(props, pa);
    }

    public Boolean connectServer() throws Exception {
//        Session session = getMailSession();
        Properties props = new Properties();
        int proxy = ReadXML.getProxy();
        Session session=null;
        if (proxy >=0){
         props.setProperty("proxySet", "true");
         props.setProperty("socksProxyHost", getAccountMail().getOutgoingServerName());
         props.setProperty("socksProxyPort",Integer.toString(getAccountMail().getPortNumber()) );
         
        }
        session= Session.getInstance(props,null);
        _store = session.getStore(getAccountMail().getIncomingServerType());
        _store.connect(getAccountMail().getIncommingServerName(), getAccountMail().getIncomingUserName(), getAccountMail().getPassword());
        return true;
    }

    public ArrayList<MailStructureDTO> getMailFormFolder(String folderName) throws MessagingException, Exception {
        if (_store.isConnected() == false) {
            connectServer();
        }
        ArrayList<MailStructureDTO> lst = new ArrayList<MailStructureDTO>();

        if (folderName == null) {
            _folder = _store.getDefaultFolder();
        } else {
            _folder = _store.getFolder(folderName);
        }
        _folder.open(Folder.READ_ONLY);

        Message message[] = _folder.getMessages();//folder.getMessages();

        int n = message.length;

        try {
            for (int i = 0; i < n; i++) {

                MailStructureDTO mail = new MailStructureDTO();
                String title = message[i].getSubject();
                mail.setTitle(title);
                String sender = "";

                try {
                    Address from[] = message[i].getFrom();
                    sender = from[0].toString();
                } catch (Exception ex) {
                    sender = "Unknow";
                }

                mail.setSender(sender);
//                Address[] to = message[i].getRecipients(Message.RecipientType.TO);
//                String lstTo = "";
//                for (int j = 0; j < to.length; j++) {
//                    lstTo += to[j].toString() + "; ";
//                }
//                mail.setRecipients(lstTo);

                //mail.setDateSend(form[1].toString());
                Date date = message[i].getSentDate();

                mail.setIsFlag(message[i].getFlags());
                if (date != null) {
//                 MailDateFormat df = new MailDateFormat();
//                 date =(Date) df.parse(date.toGMTString());
                    mail.setDateSend(date);
                }
                Object content = message[i].getContent();
//                if (content instanceof String){
//                     mail.setIsAttachment(false);
//                    mail.setContent(content.toString());
//                }else
                if (content instanceof Multipart) {
                    mail.setIsAttachment(false);
                    handleMultipart((Multipart) content, mail);
                } else {
                    mail.setIsAttachment(false);
                    mail.setContent(content.toString());
//                    handlePart((Part)content, mail);
                }

                lst.add(mail);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Không thể lấy thư này ! " + ex.getMessage());
            //folder.close(false);
            //_store.close();
            return lst;
        }

        //folder.close(false);
        //_store.close();
        return lst;

    }

    public static void handleMultipart(Multipart multipart, MailStructureDTO mail)
            throws MessagingException, IOException {
        int n = multipart.getCount();
        for (int i = 0; i < n; i++) {
            handlePart(multipart.getBodyPart(i), mail);

        }
    }

    public static void handlePart(Part part, MailStructureDTO mail)
            throws MessagingException, IOException {
        String disposition = part.getDisposition();
        String contentType = part.getContentType();
        if (disposition == null) { // When just body
            //System.out.println("Null: " + contentType);
            // Check if plain
            //MimeBodyPart mbp = (MimeBodyPart)part;
            // contentType = mbp.getContentType();
//            if ((contentType.length() >= 10) &&
//                    (contentType.toLowerCase().substring(
//                    0, 10).equals("text/plain"))) {
            if (part.isMimeType("text/plain")) {

                // part.
                String content = mail.getContent();
                content += (String) part.getContent();
                mail.setContent(content);
            } else if (part.isMimeType("text/html")) {
                String content = (String) part.getContent();
                //content = "\n" + (String) part.getContent();

                mail.setContentHTML(content);
            } else { // Don't think this will happen
                Multipart mp = (Multipart) part.getContent();
                handleMultipart(mp, mail);
//                 ByteArrayOutputStream bais = new ByteArrayOutputStream();
//               // System.out.println("Other body: " + contentType);
//                part.writeTo(bais);
//                 String content = mail.getContent();
//                content = bais.toString();
//               mail.setContent(part.getContent().toString());

//                InputStream stream = part.getInputStream();
//                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
//
//
//                while (br.ready()) {
//                   content+=br.readLine()+"\n";
//                }
            // mail.setContent(content);
            }
        } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            String filename = part.getFileName();
            if (filename != null) {
                mail.getAttachFiles().add(new File(filename));
                mail.setIsAttachment(true);
            }
//            saveFile(part.getFileName(), part.getInputStream());
        } else if (disposition.equalsIgnoreCase(Part.INLINE)) {

            String filename = part.getFileName();
            if (part.isMimeType("text/plain")) {

                // part.
                String content = mail.getContent();
                content += (String) part.getContent();
                mail.setContent(content);
            } else if (part.isMimeType("text/html")) {
                String content = (String) part.getContent();
                //content = "\n" + (String) part.getContent();

                mail.setContentHTML(content);
            }
            //mail.getNameAttachFile().add(part.getFileName());
            if (filename != null) {
                mail.getAttachFiles().add(new File(filename));
                mail.setIsAttachment(true);
            }
//            saveFile(part.getFileName(), part.getInputStream());
        } else {  // Should never happen
            System.out.println("Other: " + disposition);
        }
    }

    public static void saveFile(String filename, InputStream input, String dectination) throws IOException {
        if (filename == null) {
            filename = File.createTempFile("xx", ".out").getName();
        }
        // Do no overwrite existing file
        String fileString = dectination + File.separator + filename;
        File file = new File(fileString);
//        for (int i = 0; file.exists(); i++) {
//            file = new File(dectination + File.separator + filename + i);
//        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        BufferedInputStream bis = new BufferedInputStream(input);
        int aByte;
        while ((aByte = bis.read()) != -1) {
            bos.write(aByte);
        }
        bos.flush();
        bos.close();
        bis.close();
    }

    /**
     * @return the _accountMail
     */
    public AccountMailDTO getAccountMail() {
        return _accountMail;
    }

    /**
     * @param accountMail the _accountMail to set
     */
    public void setAccountMail(AccountMailDTO accountMail) {
        this._accountMail = accountMail;
    }

    /**
     * get session to send mail
     * @return
     */
    public static Session getMailSession(String mailServer,String host, int port) throws ParserConfigurationException, SAXException, IOException {
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties mailProperties = new Properties();
        int proxy = ReadXML.getProxy();
        //Session session=null;
        if (proxy >=0){
         mailProperties.setProperty("proxySet", "true");

         mailProperties.setProperty("socksProxyHost", host);
         mailProperties.setProperty("socksProxyPort",Integer.toString(port));

        }
        mailProperties.put("mail.smtp.starttls.enable", "true");

        mailProperties.setProperty("mail.transport.protocol", "smtp");
        //mailProperties.setProperty("mail.smtp.host", "smtp.gmail.com");
        mailProperties.setProperty("mail.smtp.host", mailServer);

        mailProperties.put("mail.smtp.auth", "true");

        Authenticator auth = new Authenticator() {
        };
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        Session session = Session.getDefaultInstance(mailProperties, auth);


        return session;
    }

    /**
     * send mail
     * @param sender address sender
     * @param pass Password mail sender
     * @param toReceiver address To receiver
     * @param CcReceiver address CC receiver
     * @param BccReceiver address BCC receiver
     * @param mail mail is sent
     * @return send sucessful or fail
     * @throws javax.mail.MessagingException
     * @throws java.io.IOException
     * @throws java.io.IOException
     */
    public static int sendMail(String mailServer, ArrayList<String> toReceiver, ArrayList<String> ccReceiver, ArrayList<String> bccReceiver, MailStructureDTO mail) throws MessagingException, IOException, IOException {
        //get session to send
        AccountMailBUS acc = new AccountMailBUS();
        AccountMailDTO accDTO = null;
        try {
            accDTO = acc.getMailFromAddress(mail.getSender());
        } catch (SQLException ex) {
            Logger.getLogger(ExcuteMailDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        String host = accDTO.getOutgoingServerName();
        int port = accDTO.getPortNumber();
        Session mailSession  = null;
        try {
            mailSession = ExcuteMailDAO.getMailSession(mailServer, host, port);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ExcuteMailDAO.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        } catch (SAXException ex) {
            Logger.getLogger(ExcuteMailDAO.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        }
        //set sender

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(mail.getSender()));
        msg.setSentDate(mail.getDateSend());
        //Add receiver , type To
        for (int i = 0; i < toReceiver.size(); i++) {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toReceiver.get(i).toString()));
        }
        //Add receiver , type Cc
        for (int i = 0; i < ccReceiver.size(); i++) {
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(ccReceiver.get(i).toString()));
        }
        //Add receiver , type Bcc
        for (int i = 0; i < bccReceiver.size(); i++) {
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bccReceiver.get(i).toString()));
        }
        //create mail to send
        //subject
        MimeBodyPart mainBodyPart = new MimeBodyPart();
        mainBodyPart.setText(mail.getContent());
        //file attach


        //collect 2 part into 1
        Multipart multi = new MimeMultipart();
        multi.addBodyPart(mainBodyPart);
        for (File file : mail.getAttachFiles()) {
            MimeBodyPart attachPart = new MimeBodyPart();
            attachPart.attachFile(file);
            multi.addBodyPart(attachPart);
        }

        //set content
        msg.setSubject(mail.getTitle());
        msg.setContent(multi);
        // create object Transport to send mail
        Transport transport = mailSession.getTransport("smtp");
        transport.connect(mailServer, mail.getSender(), mail.getPass());
        msg.saveChanges();
        //send
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        return 1;
    }
}
